# app/routers/test_conn.py
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_session
from app.db.redis import redis
from sqlalchemy import text  # ✅ 新增导入
router = APIRouter(prefix="/test", tags=["Connection Test"])


@router.get("/db")
async def test_postgres_connection(session: AsyncSession = Depends(get_session)):
    """
    测试 PostgreSQL 数据库连接
    """
    try:
        result = await session.execute(text("SELECT 1"))  # ✅ 使用 text()
        value = result.scalar_one()
        return {"status": "success", "message": f"PostgreSQL 连接正常，返回值：{value}"}
    except Exception as e:
        return {"status": "error", "message": str(e)}


@router.get("/redis")
async def test_redis_connection():
    """
    测试 Redis 连接
    """
    try:
        await redis.set("test_key", "ok", ex=10)
        val = await redis.get("test_key")
        return {"status": "success", "message": f"Redis 连接正常，读取值：{val}"}
    except Exception as e:
        return {"status": "error", "message": str(e)}
